package com.iexbuy.ihg.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.gson.reflect.TypeToken;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.SearchHistoryListAdapter;
import com.iexbuy.ihg.adapter.ShopItemListAdapter;
import com.iexbuy.ihg.adapter.YunGuoAttenceRecordsAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.BusinessType;
import com.iexbuy.ihg.entity.DistrictObject;
import com.iexbuy.ihg.entity.SearchHistory;
import com.iexbuy.ihg.entity.ShopItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class XiaoFeiSearchFragment extends BaseFragment {

	private static XiaoFeiSearchFragment homeFragmentInstent;

	@ViewInject(R.id.listView)
	private ListView listView;
	@ViewInject(R.id.mSearchText)
	private EditText mSearchText;
	@ViewInject(R.id.hotSearchGrid)
	private GridView hotSearchGrid;

	private LinearLayout listHeaderView;

	private List<String> hotSearchTexts;

	private List<ShopItemListObject> shopItemListObjects = new ArrayList<ShopItemListObject>();
	private int pageNo = 0;
	private SearchHistoryListAdapter searchHistoryListAdapter;

	private ArrayAdapter<String> adapter;

	private List<SearchHistory> searchHistorys;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_xiaofei_search, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_xiao_fei_search));

//		mSearchText.addTextChangedListener(new TextWatcher() {
//			@Override
//			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//
//			@Override
//			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//				if (charSequence!=null && StringUtil.isNotEmpty(charSequence.toString())
//						&& !StringUtil.hasStroke(charSequence.toString())) {
//
//				}
//			}
//
//			@Override
//			public void afterTextChanged(Editable editable) {}
//		});
		mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH && StringUtil.isNotEmpty(textView.getText().toString())) {
					handleSearch();
				}
				return false;
			}
		});

		refreshDate();
	}

	public void onResume() {
		super.onResume();
		initSearchHistoryData();
	}

	//刷新整个页面数据
	private void refreshDate() {
		initHotSearchData();
		initSearchHistoryData();
	}

	/**
	 * 查询列表
	 */
	private void initHotSearchData() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("mobileNo", App.sPreferences.getUserName());
		paramMap.put("latitude", "116.217421");
		paramMap.put("longitude", "39.943706");
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_HOT_SEARCH, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						hotSearchTexts = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), new TypeToken<ArrayList<String>>() {}.getType());
						initHotSearchView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initHotSearchView() {
		hotSearchGrid.setAdapter(new BaseAdapter() {
			@Override
			public int getCount() {
				return hotSearchTexts.size();
			}

			@Override
			public Object getItem(int i) {
				return hotSearchTexts.get(i);
			}

			@Override
			public long getItemId(int i) {
				return 1;
			}

			@Override
			public View getView(int i, View view, ViewGroup viewGroup) {
				if (view == null) {
					view = mBaseActivity.getLayoutInflater().from(mBaseActivity).inflate(R.layout.fragment_xiaofei_district_hot_item, null);
				}
				view.setTag(hotSearchTexts.get(i));
				((TextView) view).setText(hotSearchTexts.get(i));
				return view;
			}
		});
		hotSearchGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				mSearchText.setText(view.getTag().toString());
				handleSearch();
			}
		});
	}

	private void initSearchHistoryData() {
		try {
			searchHistorys = App.db.findAll(SearchHistory.class);
			initSearchHistoryView();
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	private void initSearchHistoryView() {
		if (searchHistoryListAdapter == null) {
			searchHistoryListAdapter = new SearchHistoryListAdapter(mBaseActivity, searchHistorys);
			listView.setAdapter(searchHistoryListAdapter);
		}
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				XiaoFeiSearchResultFragment.setSearch(searchHistorys.get(i).getKeyword());
				CommUtil.openSingleFragmentActivity(mBaseActivity, XiaoFeiSearchResultFragment.class);
			}
		});
		searchHistoryListAdapter.notifyDataSetChanged();
	}

	@OnClick(R.id.searchBtn)
	private void searchBtnClick(View view) {
		handleSearch();
	}

	private void handleSearch() {
		try {
			SearchHistory sh = App.db.findFirst(Selector.from(SearchHistory.class).where("keyword", "=", mSearchText.getText().toString()));
			if (sh == null) {
				App.db.save(new SearchHistory(mSearchText.getText().toString()));
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
		XiaoFeiSearchResultFragment.setSearch(mSearchText.getText().toString());
		CommUtil.openSingleFragmentActivity(mBaseActivity, XiaoFeiSearchResultFragment.class);
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static XiaoFeiSearchFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
